package cn.xenosp.server.common.logs;

import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 项目名： util
 * 包路径： com.logs
 * 作者：   TongHui
 * 创建时间: 2024-07-19 16:49
 * 描述: TODO
 * 版本: 1.0
 */
public class FileFilterUtil {

    FilenameFilter filter = null;

    public FileFilterUtil(String pattenExpression) {
        this.filter = new MyFilenameFilter(pattenExpression);
    }

    public void listFilesByFilenameFilter(String dirName, List<File> fileList) {
        File dirFile = new File(dirName);
        if (!dirFile.exists()) {
            System.out.println("获取文件失败，找不到目录：" + dirName);
        } else {
            if (dirFile.isFile()) {
                boolean flag = this.filter.accept(dirFile.getParentFile(), dirFile.getName());
                if (flag) {
                    fileList.add(dirFile);
                }
            }

            if (dirFile.isDirectory()) {
                File[] files = dirFile.listFiles(this.filter);

                for(int i = 0; i < files.length; ++i) {
                    if (files[i].isFile()) {
                        if (fileList == null) {
                            fileList = new ArrayList();
                        }

                        fileList.add(files[i]);
                    } else if (files[i].isDirectory()) {
                        this.listFilesByFilenameFilter(files[i].getAbsolutePath(), fileList);
                    }
                }
            }

        }
    }



    class MyFilenameFilter implements FilenameFilter {
        private String pattenExpression = "";

        public MyFilenameFilter(String pattenExpression) {
            this.pattenExpression = pattenExpression.replaceAll("(\\*)+", ".*");
        }

        public boolean accept(File dir, String name) {
            File file = new File(dir, name);
            if (file.isFile()) {
                String filePath = file.getAbsolutePath();
                if (File.separatorChar == '\\') {
                    filePath = filePath.replaceAll("\\\\", "/");
                }

                Pattern p = Pattern.compile(this.pattenExpression);
                Matcher match = p.matcher(filePath);
                return match.find();
            } else {
                return true;
            }
        }
    }
}
